package com.huang.leetcode.stack;

import java.util.Stack;

/**
 * @Author：CreateSequence
 * @Date：2020-08-01 13:09
 * @Description：逆波兰表达式求值
 */
public class PB105 {

    public int evalRPN(String[] tokens) {
        /**
         * 1.创建一个数字栈，遍历字符数组：
         * 1.1 当遇到数字的时候入栈
         * 1.2 当遇到计算符号的时候连续出栈两个元素并计算，将结果入栈
         * 2.当计算结束以后，栈中唯一元素即为计算结果
         */

        Stack<Integer> stack = new Stack<>();
        Integer n1, n2 = 0;
        for (String s : tokens) {
            switch (s) {
                case "+":
                    n2 = stack.pop();
                    n1 = stack.pop();
                    stack.push(n1 + n2);
                    break;
                case "-":
                    n2 = stack.pop();
                    n1 = stack.pop();
                    stack.push(n1 - n2);
                    break;
                case "*":
                    n2 = stack.pop();
                    n1 = stack.pop();
                    stack.push(n1 * n2);
                    break;
                case "/":
                    n2 = stack.pop();
                    n1 = stack.pop();
                    stack.push(n1 / n2);
                    break;
                default:
                    stack.push(Integer.parseInt(s));
                    break;
            }
        }
        return stack.pop();
    }

}
